//
//  USAddOurListGroupController.m
//  us
//
//  Created by karry on 2025/5/7.
//

#import "USAddOurListGroupController.h"
#import "IQKeyboardManager.h"
#import "USOurListView.h"
#import "USColorPickerView.h"
#import "USInputCell.h"

@interface USAddOurListGroupController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) USOurListView *listView;

@property (nonatomic,strong) NSArray <DTItem *>*items;

@property (nonatomic,strong) NSMutableArray<NSString *> *vividMacaronColors;

@end

@implementation USAddOurListGroupController


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.prefersLargeTitles = NO;
    [IQKeyboardManager sharedManager].enable = YES;
    IQKeyboardManager.sharedManager.enableAutoToolbar = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (!self.dayModel) {
        self.dayModel = [USListModel new];
        self.dayModel.color = @"#E985A6";
    }
    
    [self setupData];
    
    [self setupView];
}

- (void)setupData{
    
    self.items = @[[DTItem itemWithTitle:@"名称" image:[UIImage imageNamed:@"ic_ds_1"] tag:0 identifier:nil handle:nil]];
}

- (void)setupView{
    
    self.navigationItem.rightBarButtonItem  = self.doneItem;

    RAC(self.doneItem, enabled) = [RACObserve(self.dayModel, challengeTitle) map:^id _Nullable(NSString *text) {
        return @(text.length > 0);
    }];
    
    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 145 + 20 * 2)];
    [self.view addSubview:header];
    
    self.listView = [[USOurListView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    self.listView.color = [UIColor jk_colorWithHexString:self.dayModel.color];
    self.listView.titleLab.text = self.dayModel.challengeTitle;
    if (self.dayModel.taskCount == 0) {
        self.listView.progressView.progress = 0.0;
    }else{
        self.listView.progressView.progress = self.dayModel.completedTaskCount * 1.0/self.dayModel.taskCount * 1.0;
    }
    self.listView.progressLab.text = [NSString stringWithFormat:@"%li/%li",self.dayModel.completedTaskCount,self.dayModel.taskCount];
    
    [self.listView us_addShadow];
    [header addSubview:self.listView];
    
    [header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.height.mas_equalTo(header.jk_height);
    }];
    
    [self.listView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(header);
        make.width.mas_equalTo(168);
        make.height.mas_equalTo(145);
    }];
    
    UIView *pickerHeader = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 22 + 20 * 2)];
    
    USColorPickerView *colorPickerView = [[USColorPickerView alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 22)];
    @weakify(self)
    colorPickerView.colorSelectedBlock = ^(UIColor * _Nonnull color) {
        @strongify(self)
        self.dayModel.color = color.jk_HEXString;

        self.listView.color = color;
    };
    
    [colorPickerView setColorHexList:[self.vividMacaronColors copy]];
    [pickerHeader addSubview:colorPickerView];
    [colorPickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_offset(0);
        make.height.mas_equalTo(22);
    }];
    
    
    USDashedLineView *lineView = [[USDashedLineView alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, 1.4)];
    [pickerHeader addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(16);
        make.right.mas_offset(-16);
        make.top.mas_equalTo(colorPickerView.mas_bottom).mas_offset(20);
        make.height.mas_equalTo(1.4);
    }];
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleInsetGrouped];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = UIColor.clearColor;
    _tableView = tableView;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableHeaderView = pickerHeader;
    [self.tableView registerClass:[USInputCell class] forCellReuseIdentifier:@"USInputCellId"];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_equalTo(header.mas_bottom);
    }];
    
    [self.tableView reloadData];
    
    
    
}


- (void)startUpload{
    [self.indicator startAnimating];
    UIBarButtonItem *loadingItem = [[UIBarButtonItem alloc] initWithCustomView:self.indicator];
    self.navigationItem.rightBarButtonItem = loadingItem;
    self.view.userInteractionEnabled = NO; // 禁用整个页面操作

    
}
- (void)endUpLoad{
    self.navigationItem.rightBarButtonItem = self.doneItem;
    [self.indicator stopAnimating];
    self.view.userInteractionEnabled = YES;
}
- (void)doneAction:(id)sender{
    [super doneAction:sender];
    [USFeedbackTool impactSoft];
  
    
    [self startUpload];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"challengeTitle"] = self.dayModel.challengeTitle?:@"";
    params[@"color"] = self.dayModel.color?:@"";

    NSString *path = API_DailyChallengeAdd;
    if (self.isEdit) {
        path = API_DailyChallengeEdit;
        params[@"sweetChallengeId"] = self.dayModel.sweetChallengeId;
    }
    
    NSLog(@"params = %@",params);
    [[EMNetWork shareManager] em_post:path
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {

        [self endUpLoad];
        if (!api.success) {
            return;
        }
        [USFeedbackTool notifySuccess];
        [self.navigationController popViewControllerAnimated:YES];
        
    } fail:^{
        
        [self endUpLoad];

    }];
    
    
}

- (NSMutableArray <NSString *>*)vividMacaronColors {
    if (_vividMacaronColors == nil) {
        NSArray<NSString *> *colors = @[
            // 🌸 粉红
            @"#E985A6", @"#E15A87",
            // 🔴 红
            @"#E98585", @"#E15A5A",
            // 🟠 橙
            @"#E9AF85", @"#E1925A",
            // 🟡 黄
            @"#E9D885", @"#E1CB5A",
            // 🟢 绿
            @"#96E985", @"#70E15A",
            // 🔵 蓝
            @"#85B7E9", @"#5A9EE1",
            // 🟦 青
            @"#85E9D8", @"#5AE1CB",
            // 🟣 紫
            @"#B785E9", @"#9E5AE1",
        ];
        _vividMacaronColors = [NSMutableArray arrayWithArray:colors];

    }
    return _vividMacaronColors;
}

#pragma mark - <UITableViewDataSource,UITableViewDelegate>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    USInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USInputCellId"];
    
    DTItem *item = self.items[indexPath.row];
    
    cell.inputField.placeholder = @"请输入";
    //    cell.inputField.text = self.dayModel.challengeTitle;
    [cell configureWithTitle:item.title image:item.image inputText:self.dayModel.challengeTitle];
    
    @weakify(self);
    
//    [[[cell.inputField.rac_textSignal distinctUntilChanged] skip:1]
//     subscribeNext:^(NSString * _Nullable text) {
//        @strongify(self);
//        
//        self.dayModel.challengeTitle = text;
//        self.listView.titleLab.text = text;
//        
//    }];
//    
    [[cell.inputField.rac_textSignal distinctUntilChanged] subscribeNext:^(NSString * _Nullable text) {
        @strongify(self);
        
        // 限制最多20字符
        if (text.length > 20) {
            text = [text substringToIndex:20];
            cell.inputField.text = text; // 更新输入框内容
        }
        self.dayModel.challengeTitle = text;
        self.listView.titleLab.text = text;
        
    }];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 68;
}


@end
